import {buildTree, deepCopy, importView} from '@/common/utils';
import Store from '@/store';

class Initialization {
	async init() {
		if (!Store.getters.loginStatus) {
			return true;
		}
		return await Store.dispatch('getMenus');
	}

	generateMenuTree(menus) {
		return buildTree(menus, 'menuId', 'parentId')
	}

	/**
	 *
	 * @param tree
	 * @returns {{path: string, component: (function(): Promise<*>), children: {path: *, component: function(): Promise<*>, mate: {visible: *, icon: *, menuName: *}, name: *}[], name: string}}
	 */
	generateRouter(tree) {
		tree = deepCopy(tree)
		return {
			name: 'Admin',
			path: '/admin',
			component: () => import('@/components/layout/AdminLayout'),
			children: this.#buildRouter(tree)
		}
	}

	#buildRouter(tree = []) {
		return tree.map(item => {
			let route = {
				name: item.name,
				path: item.path,
				component: importView(item.component),
				mate: {
					icon: item.icon,
					visible: item.visible,
					menuName: item.menuName
				}
			}
			if (item.children && item.children.length > 0) {
				route.children = this.#buildRouter(item.children)
			}
			return route;
		})
	}
}


export default new Initialization();